package com.hao;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class CTopic2 {
        public static void main(String[] args) throws IOException, TimeoutException {
            ConnectionFactory factory = new ConnectionFactory();
            String queue1Name="test_topic_queue1";
            factory.setHost("8.130.120.148");
            factory.setPort(5672);

            factory.setVirtualHost("/kaiyuan");
            factory.setUsername("shihao");
            factory.setPassword("shihao");
            // 创建连接Connection
            Connection connection = factory.newConnection();
            // 创建Channel
            Channel channel = connection.createChannel();

            DefaultConsumer consumer = new DefaultConsumer(channel){
                /**
                 * 回调方法，收到消息式会自动执行该方法
                 * @param consumerTag the <i>consumer tag</i> associated with the consumer
                 * @param envelope packaging data for the message
                 * @param properties content header data for the message
                 * @param body the message body (opaque, client-specific byte array)
                 * @throws IOException
                 */
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {

                    System.out.println("body："+new String(body));
                    System.out.println("保存在数据库 CTopic2");
                }
            };
            channel.basicConsume(queue1Name,true,consumer);

        }
    }

